package com.stanwind.controller.commons;

import com.stanwind.api.Log;
import com.stanwind.api.NumberUtils;
import com.stanwind.constant.ResponseState;
import com.stanwind.constant.ServerSetting;
import com.stanwind.domain.model.Account;
import com.stanwind.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;

/**
 * Created by StanWind on 2017/2/14.
 */
@Controller
public class RegController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private Log log;

    @Autowired
    private NumberUtils numberUtils;

    @RequestMapping(value = "reg", method = RequestMethod.POST)
    public
    @ResponseBody
    Object reg(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username == null || username.equals("") || password == null || password.equals(""))
            return ResponseState.REG_NULL.convertToJsonObject();

        Account account = this.accountService.getAccountByAccount(username);
        if (account != null)
            return ResponseState.REG_EXIST.convertToJsonObject();

        Random random = new Random();
        //生成salt
        String salt = "" + numberUtils.getRandomInt(1000000, 9999999);
        //生成accountid
        String accountId = getRandomAccountId();

        account = new Account();
        account.setAccount(username);
        account.setPasswordMd5(numberUtils.MD5(password + salt));
        account.setSalt(salt);
        account.setAccountId(accountId);
        account.setAccountType(ServerSetting.ACC_TYPE);


        this.accountService.insert(account);


        account = this.accountService.getAccountByAccount(username);
        if (account != null)
            return ResponseState.REG_OK.convertToJsonObject();
        return ResponseState.REG_ERROR.convertToJsonObject();
    }



    /**
     * 获得一个新的accountid
     *
     * @return 生成的Account ID
     */
    private String getRandomAccountId() {
        List<Account> accounts = this.accountService.listAll();
        String account_id = ServerSetting.ACCID_PREFIX + (accounts.size() + 1) + numberUtils.getRandomInt(10000, 99999);
        return account_id;
    }
}
